//
//  HomeChatView.swift
//  聊天总览
//
//  Created by 小柠檬🍋 on 2025/9/7.
//

import SwiftUI

struct ChatFunctionView: View {
    @StateObject var viewModel = ChatFunctionViewModel()
    // 定义2列的网格布局
    private let columns = [
        GridItem(.flexible(), spacing: 15),
        GridItem(.flexible(), spacing: 15)
    ]
    
    var body: some View {
        ZStack{
            if !viewModel.status.isEmpty {
                HomeEmptyView(text1: viewModel.status)
            } else {
                ScrollView {
                    //需要嵌套一层LazyVStack，不然会产生间距，而且大小还会随机
                    LazyVStack(spacing: 10) {
                        ForEach(viewModel.items,id: \.id) { item in
                            switch item {
                            case .title(let titleBean):
                                // 标题视图 - 单行显示
                                ChatListTitleView(bean: titleBean)
                                    .padding(.horizontal, 23)
                            case .functions(let functionBeans):
                                // 功能项视图 - 网格布局
                                LazyVGrid(columns: columns, spacing: 15) {
                                    ForEach(functionBeans) { bean in
                                        ChatFunctionItemView(bean: bean)
                                    }
                                }
                                .padding(.horizontal, 20)
                            }
                        }
                        LoadMoreFooter(refreshing: $viewModel.footerRefreshing, action: {
                            viewModel.getData()
                        }) {
                            LoadMoreView(noMore: viewModel.noMore, footerRefreshing: viewModel.footerRefreshing, hideNoMore: true)
                        }
                        .noMore(viewModel.noMore)
                        .preload(offset: 10)
                    }
                }
                .enableRefresh()
            }}
        .onAppear{
            if !viewModel.isInit {
                viewModel.getData()
                viewModel.isInit = true
            }
        }
    }
}

//#Preview {
//    ChatListView()
//}

//定义预览提供者
struct ChatFunctionView_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for: ChatFunctionView().background(.bg))
    }
}
